package com.coincalf.wallet.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.coincalf.wallet.entity.SyncBlockHeight;
import com.coincalf.wallet.mapper.SyncBlockHeightMapper;
import com.coincalf.wallet.service.SyncBlockHeightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Transactional(rollbackFor = Exception.class)
public class SyncBlockHeightServiceImpl extends ServiceImpl<SyncBlockHeightMapper, SyncBlockHeight> implements SyncBlockHeightService {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public SyncBlockHeight selectOneByCoinId(long coinId) {
        EntityWrapper<SyncBlockHeight> wrap = new EntityWrapper<>();
        wrap.eq("coin_id", coinId);
        return super.selectOne(wrap);
    }

    @Override
    public SyncBlockHeight selectOneByCoinName(String coinName) {
        EntityWrapper<SyncBlockHeight> wrap = new EntityWrapper<>();
        wrap.eq("coin_name", coinName);
        return super.selectOne(wrap);
    }

    @Override
    public boolean updateOne(SyncBlockHeight syncBlockHeight) {
        return super.updateById(syncBlockHeight);
    }

    @Override
    public Long getCoinIdByCoinName(String coinName) {
        String redisCoinName = "coin:id:" + coinName;
        Long coinId = (Long) redisTemplate.opsForValue().get(redisCoinName);
        if (coinId != null) {
            return coinId;
        }
        SyncBlockHeight result = super.selectOne(new EntityWrapper<SyncBlockHeight>().eq("coin_name", coinName));
        coinId = result.getCoinId();
        redisTemplate.opsForValue().set(redisCoinName, coinId, 5, TimeUnit.MINUTES);
        return coinId;
    }

}
